package com.muki.succ.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.muki.spider.Spider;
import com.muki.succ.registery.RegisteryCenter;
import com.muki.succ.registery.SpiderCore;
import com.muki.succ.web.service.SpiderService;

@Service
public class SpiderServiceImpl implements SpiderService{

	private volatile Map<String,Thread> threads = new HashMap<>();

	@Override
	public List<Spider> runningSpiders() {
		Map<String,Spider> spiders = RegisteryCenter.spiders;
		List<Spider> list = new ArrayList<>();
		for(Spider spider:spiders.values()) {
			/**
			 * 一层过滤
			 */
			if(spider!=null)
				list.add(spider);
		}
		return list;
	}

	@Override
	public List<Spider> waitingSpiders() {
		return null;
	}

	@Override
	public void createSpider(String theme) {
		RegisteryCenter.getInstance().createSpiderTopicListener(theme);
	}

	@Override
	public void startSpider(String name) {
		Thread thread = threads.getOrDefault(name, null);
		Spider sp = RegisteryCenter.spiders.getOrDefault(name,null);
		if(thread!=null) {
			if(!thread.isInterrupted()) {
				sp.setStatus(true);
				RegisteryCenter.spiders.put(name, sp);
				thread.notify();
			}
			return ;
		}
		if(sp!=null) {
			thread = new Thread(SpiderCore.newInstance(sp));
			threads.put(name, thread);
			thread.start();
		}
	}

	@Override
	public void shutDownSpider(String name) {
		Thread thread = threads.getOrDefault(name, null);
		if(thread!=null && thread.isAlive()) {
			try {
				Spider sp = RegisteryCenter.spiders.get(name);
				sp.setStatus(false);
				RegisteryCenter.spiders.put(name, sp);
				thread.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public List<Spider> unBindSpiders() {
		Map<String,Spider> currentSpiders = RegisteryCenter.spiders;
		List<Spider> list = new ArrayList<>();
		for(Spider spider:currentSpiders.values()) {
			if(spider.getUrl()==null) {
				list.add(spider);
			}
		}
		return list;
	}

	@Override
	public void bindStartUrl(String name, String startUrl) {
		
	}

}
